#include <linux/uinput.h>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <thread>
#include <chrono>

#define LONG_BITS (sizeof(long) * 8)
#define NLONGS(x) (((x) + LONG_BITS - 1) / LONG_BITS)

static const char *INPUT_NODE = "/dev/input/event1";

void SleepOneSecond() {
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}

static inline int bit_is_set(const unsigned long *array, int bit) {
    return !!(array[bit / LONG_BITS] & (1LL << (bit % LONG_BITS)));
}

int main() {
    int fd = open(INPUT_NODE, O_WRONLY | O_NONBLOCK);
    std::cout << "get fd: " << fd << std::endl;

    int rc = 0;
    int i = 0;
    int keyVal = 0;
    unsigned long keystate[NLONGS(KEY_CNT)] = { 0 };
    while (true) {
        // Query all key state
        rc = ioctl(fd, EVIOCGKEY(sizeof(keystate)), keystate);
        if (rc < 0) {
            std::cout << "read all key state failed, rc: " << rc << std::endl;
            SleepOneSecond();
            continue;
        }

        for (i = 0; i < KEY_CNT; i++) {
        	keyVal = bit_is_set(keystate, i);
        	if (keyVal != 0) {
        		std::cout << "KEY_IDX: " << i << " is set" << std::endl;
        	}
        }

        SleepOneSecond();
        std::cout << "#####################Loop Query#####################" << std::endl;
    }

    if (fd > 0) {
    	close(fd);
    	fd = 0;
    }
    return 0;
}

